﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using QuickCode.Application.DTO;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Util;

namespace QuickCode.WebApi.Controllers
{
    /// <summary>
    /// 鉴权相关
    /// </summary>
    [Route("Api/Auth")]
    [ApiExplorerSettings(GroupName = "Authorize")]
    public class AuthController : BaseController
    {
        readonly IConfiguration _config;
        public AuthController(IConfiguration config)
        {
            _config = config;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("Login")]
        [ProducesResponseType(typeof(LoginDTO), StatusCodes.Status200OK)]
        public WebApiPackage<LoginDTO> Login(UserDTO dto)
        {
            #region 校验用户信息，假设此处我们已经校验成功

            #endregion
            var view = new LoginDTO
            {
                Expires = DateTime.Now.AddDays(30)
            };
            var claims = new[] { new Claim(ClaimTypes.NameIdentifier, "") };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Logging:tokenManagement:secret"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: _config["Logging:tokenManagement:issuer"],
                audience: _config["Logging:tokenManagement:audience"],
                claims: claims,
                expires: view.Expires,
                signingCredentials: creds);
            view.Token = "Bearer " + new JwtSecurityTokenHandler().WriteToken(token);
            return Data(view);
        }
    }
}
